<!--
 * @Description: 新核心-嵌入授权中间页面
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 03/12/24 PM1:39
 -->
<!--setup-->
<script setup>
import { onMounted, getCurrentInstance, ref } from 'vue'
import useUserStore from '@/store/use-user-store'
import useMenuStore from '@/store/use-menu-store'
import { useRouterPlus } from '@/router/use-router-plus'
// import BaseEmptyView from '@shared/base/base-empty-view'
import { to, parseJsonNoError } from 'sf-utils2'

const { proxy } = getCurrentInstance()
const props = defineProps({})
const emit = defineEmits([])

/* 状态 */
const loading = ref(false)
const userStore = useUserStore()
const menuStore = useMenuStore()
const { route, router } = useRouterPlus()
const errorInfo = ref()
const DEFAULT_HOME_PAGE = '/home' // 默认首页地址

const BASE_STORAGE_KEY = '__store__base__0.0.0' // 新核心存储key

/* 方法 */

/**
 * 解码字符串
 */
function decodeString(val) {
  return decodeURIComponent(decodeURIComponent(val || ''))
}

/**
 * 初始化
 */
async function init() {
  let token = decodeString(route.query._t || '')
  if (!token) {
    const storeData = parseJsonNoError(localStorage.getItem(BASE_STORAGE_KEY)) || {}
    token = storeData?.token
  }

  if (!token) return (errorInfo.value = { msg: '授权失败，缺少必要参数[token]' })

  // 清除用户信息
  userStore.clearUserInfo()

  userStore.token = token

  loading.value = true
  await to(Promise.all([userStore.getUserInfo(), userStore.getUserDeparts(), menuStore.getUserAuthMenus()]))
  loading.value = false

  const redirectUri = decodeString(route.query.redirectUri || '')
  if (redirectUri) {
    if (/^https?/.test(redirectUri)) {
      // 如果是http 开头
      return window.location.replace(redirectUri)
    }
    return router.replace({
      path: redirectUri
    })
  }

  // 默认跳转到首页
  return router.replace({
    path: DEFAULT_HOME_PAGE
  })
}

/* 计算 */

/* 监听 */

/* 周期 */
init()
onMounted(() => {})

/* 暴露 */
defineExpose({
  $: proxy.$
})
</script>

<!--render-->
<template>
  <div
    v-spin="{
      loading,
      showLoadingText: true,
      loadingText: `页面正在加载中... `,
      isFakeProgressText: true,
      mask: false,
      type: 'circle2'
    }"
    class="h-100vh w-100vw flex-center relative bg-[#fff]"
  >
    <el-empty
      v-if="errorInfo?.msg"
      :description="errorInfo?.msg"
      class="mb-[10%]"
    />
  </div>
</template>

<!--style-->
<style scoped lang="less"></style>
